package com.sinping.qh.service.admin.impl;

import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.sinping.qh.api.support.*;
import com.sinping.qh.domain.common.UnitDomain;
import com.sinping.qh.domain.common.UploadImage;
import com.sinping.qh.domain.common.UploadImageBase64Bean;
import com.sinping.qh.domain.lab.LabInspectItemRelationDomain;
import com.sinping.qh.domain.lab.LabInspectItemTreeDomain;
import com.sinping.qh.domain.lab.LaboratoryDomain;
import com.sinping.qh.domain.records.CheckRecord;
import com.sinping.qh.domain.records.HiddendangerRecord;
import com.sinping.qh.domain.records.RectifyReviewDomain;
import com.sinping.qh.dto.admin.lab.LaboratoryDto;
import com.sinping.qh.dto.admin.noticebook.NoticeBookExportWordDto;
import com.sinping.qh.dto.admin.noticebook.NoticeBookReturnDto;
import com.sinping.qh.dto.admin.record.GenerateReportByHiddendangerRecordDto;
import com.sinping.qh.dto.admin.record.HiddendangerRecordDetailDto;
import com.sinping.qh.dto.admin.record.HiddendangerRecordDto;
import com.sinping.qh.dto.admin.record.RectifyReviewDto;
import com.sinping.qh.query.records.HiddenDangerRecordQuery;
import com.sinping.qh.repository.mongo.RectifyReviewRepository;
import com.sinping.qh.repository.mongo.UnitRepository;
import com.sinping.qh.repository.mongo.common.UploadImageRepository;
import com.sinping.qh.repository.mongo.lab.LabInspectItemRelationRepository;
import com.sinping.qh.repository.mongo.lab.LabInspectItemTreeRepository;
import com.sinping.qh.repository.mongo.lab.LaboratoryRepository;
import com.sinping.qh.repository.mongo.records.CheckRecordsRepository;
import com.sinping.qh.repository.mongo.records.HiddenDangerRecordRepository;
import com.sinping.qh.repository.mongo.records.impl.RectifyReviewRepositoryImpl;
import com.sinping.qh.service.MongoManager;
import com.sinping.qh.service.admin.IHiddenDangerRecordService;
import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.misc.IdGenerator;
import com.sinping.qh.utils.time.DateFormatUtil;
import com.sinping.qh.utils.word.Base64Util;
import com.sinping.qh.utils.word.DocumentHandler;
import com.sinping.qh.utils.worddocx.WordTools;
import org.apache.commons.lang3.StringUtils;
import org.docx4j.Docx4J;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 隐患记录实现类
 *
 * @author Tiansx
 * @create 2018-06-05 15:33
 **/
@Service
public class HiddenDangerRecordServiceImpl implements IHiddenDangerRecordService {


    @Value(value = "${qh.upload.filePath}")
    private String filePath;

    @Value(value = "${qh.upload.urlPath}")
    private String urlPath;

    @Autowired
    private HiddenDangerRecordRepository hiddenDangerRecordRepository;

    @Autowired
    private LaboratoryRepository laboratoryRepository;

    @Autowired
    private RectifyReviewRepository rectifyReviewRepository;

    @Autowired
    private RectifyReviewRepositoryImpl rectifyReviewRepositoryImpl;

    @Autowired
    private UploadImageRepository uploadImageRepository;

    @Autowired
    private MongoManager mongoManager;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    private CheckRecordsRepository checkRecordsRepository;

    @Autowired
    private LabInspectItemRelationRepository labInspectItemRelationRepository;

    @Autowired
    LabInspectItemTreeRepository labInspectItemTreeRepository;

    @Autowired
    UnitRepository unitRepository;

    @Override
    public ResDto getHiddenDangerRecordList(FrontPage page) {
        /**
         * 检查记录状态 0-未检查；1-检查中；2-待审核；3-已审核
         */
        Integer pageSize = page.getSize();
        Integer pageNum = page.getPage();

        //2.Map conditionMap
        Map<String, Object> conditionMap = page.getCondition();
        HiddenDangerRecordQuery hiddenDangerRecordQuery = new HiddenDangerRecordQuery();
        hiddenDangerRecordQuery.setCheckUnitId((String) conditionMap.get("check_unit_id"));
        hiddenDangerRecordQuery.setCheckBuildingId((String) conditionMap.get("check_building_id"));
        hiddenDangerRecordQuery.setCheckStatus((String) conditionMap.get("check_status"));
        ArrayList<String> hidden_danger_statusList = (ArrayList<String>) conditionMap.get("hidden_danger_status");
        if (hidden_danger_statusList == null) {
            hiddenDangerRecordQuery.setHidden_danger_status(null);
        } else if (hidden_danger_statusList.isEmpty()) {
            hiddenDangerRecordQuery.setHidden_danger_status(null);
        } else {
            hiddenDangerRecordQuery.setHidden_danger_status(hidden_danger_statusList);
        }

        hiddenDangerRecordQuery.setOffices((String) conditionMap.get("offices"));
        try {
            String startDate = (String) conditionMap.get("start_date");
            String endDate = (String) conditionMap.get("end_date");

            if (!StringUtils.isEmpty(startDate)) {
                hiddenDangerRecordQuery.setStartDate(DateFormatUtil.pareDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, startDate));
            } else {
                hiddenDangerRecordQuery.setStartDate(null);

            }
            if (!StringUtils.isEmpty(endDate)) {
                hiddenDangerRecordQuery.setEndDate(DateFormatUtil.pareDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, endDate));
            } else {
                hiddenDangerRecordQuery.setEndDate(null);

            }
        } catch (ParseException e) {
            e.printStackTrace();
            return new ResDto(Const.PARAM_ERROR, "时间格式不正确");

        }
        String order = "DESC";
        if (!StringUtils.isEmpty(page.getOrder())) {
            if ("ASC".equals(page.getOrder().toUpperCase())) {
                order = "ASC";
            }
        }
        String prop = "gmt_created";
        if (!StringUtils.isEmpty(page.getProp())) {
            prop = page.getProp();
        }

        //设置查询条件
        Pageable pageRequest = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.fromString(order), prop));
        //6.用MongoManager去查询的数据
        Page<HiddendangerRecord> pageResult = mongoManager.findPage(hiddenDangerRecordQuery, pageRequest, HiddendangerRecord.class);

        //7.把查询结果放到FrontPage中返回到接口
        ResDto resDto = new ResDto(ConstEum.SUCCESS);

        ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(resDto, pageResult, HiddendangerRecordDto.class, page);


        return resDto;
    }

    @Override
    public ResDto getHiddenDangerRecordDetail(String id) {
        HiddendangerRecord one = hiddenDangerRecordRepository.findOne(id);
        if (one == null) {
            return new ResDto(Const.SERVER_ERROR, "记录不存在");
        }
        List<RectifyReviewDomain> rectifyReviewDomainList = rectifyReviewRepository.findAllByHiddenDangerIdOrderByGmtModifiedAsc(one.getId());

        List<RectifyReviewDomain> rectifyReviewDomainListNew = BeanMapper.mapList(rectifyReviewDomainList, RectifyReviewDomain.class);


        RectifyReviewDomain rectifyReviewDomainNew = new RectifyReviewDomain();
        if (one.getCaseGmtCreate() != null) {
            rectifyReviewDomainNew.setId(one.getId());
            rectifyReviewDomainNew.setReType("3");
            rectifyReviewDomainNew.setHiddenDangerStatus(one.getHiddenDangerStatus());
            rectifyReviewDomainNew.setDesc(one.getCaseMethod());
            rectifyReviewDomainNew.setSubmitTime(one.getCaseGmtCreate());
            rectifyReviewDomainNew.setPreTime(one.getPreTime());
            rectifyReviewDomainNew.setSubmitUserId(one.getCaseUserNameId());
            rectifyReviewDomainNew.setSubmitUserName(one.getCaseUserName());
            rectifyReviewDomainNew.setHiddenDangerId(one.getId());
            rectifyReviewDomainNew.setGmtCreated(one.getCaseGmtCreate());
            rectifyReviewDomainNew.setGmtModified(one.getCaseGmtCreate());
        }
        for ( RectifyReviewDomain rectifyReviewDomain:rectifyReviewDomainList) {
            int i=rectifyReviewDomainList.indexOf(rectifyReviewDomain);
            //是否要插入整改方案 app用到
            if (one.getCaseGmtCreate() != null && one.getCaseGmtCreate().before(rectifyReviewDomain.getGmtModified())) {
                if (!rectifyReviewDomainListNew.contains(rectifyReviewDomainNew)) {
                    rectifyReviewDomainListNew.add(i, rectifyReviewDomainNew);
                }
            }
        }

        if (one.getCaseGmtCreate() != null && !rectifyReviewDomainListNew.contains(rectifyReviewDomainNew)) {
            rectifyReviewDomainListNew.add(rectifyReviewDomainNew);
        }


        HiddendangerRecordDetailDto hiddendangerRecordDetailDto = BeanMapper.map(one, HiddendangerRecordDetailDto.class);

        hiddendangerRecordDetailDto.setRectifyReviewList(rectifyReviewDomainListNew);
        String data = JsonMapper.defaultMapper().toJson(hiddendangerRecordDetailDto);

        return new ResDto(ConstEum.SUCCESS, data);
    }


    /**
     * 统计隐患记录隐患数
     */
    @Override
    public ResDto getHiddenDangerRecordStatistics(String msg) {

//        try {
//            List<DBObject> list = new ArrayList<>();
//
//            Map<String, String> map = JsonMapper.defaultMapper().fromJson(msg, Map.class);
//            if (map == null) {
//                return new ResDto(Const.SERVER_ERROR, "json格式有误");
//            }
//
//            //条件查询
//            /*按检查项查询*/
//            Map<String, Object> matchMap = new HashMap<>();
//            if (StringUtils.isNotBlank(map.get("level")) && StringUtils.isNotBlank(map.get("check_item_id"))) {
//                String level = map.get("level").toString();
//                String check_item_id = map.get("check_item_id");
//                if (level.equals("1")) {
//                    matchMap.put("check_item_one_id", check_item_id);
//                } else if (level.equals("2")) {
//                    matchMap.put("check_item_two_id", check_item_id);
//                }
//            }
//            Map<String, Object> timeMap = new HashMap<>();
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//            /*按日期查询*/
//            if (!StringUtils.isBlank(map.get("start_date"))) {
//
//                Date start_date = simpleDateFormat.parse(map.get("start_date").toString());
//                timeMap.put("$gte", start_date);
//            }
//            if (!StringUtils.isBlank(map.get("end_date"))) {
//                Date end_date = simpleDateFormat.parse(map.get("end_date").toString());
//                timeMap.put("$lte", end_date);
//            }
//            if (timeMap.size() > 0) {
//                matchMap.put("gmt_created", timeMap);
//            }
//            matchMap.put("check_status", "3"); //状态为”已审核“的检查记录中的隐患记录
//
//            DBObject match = new BasicDBObject("$match", matchMap);
//            list.add(match);
//
//            /* 创建group1操作 */
//            Map<String, String> groupIdMap = new HashMap<>();
//            groupIdMap.put("unit_id", "$check_unit_id");
//            groupIdMap.put("unit_name", "$check_unit");
//
//            Map<String, Object> group1Map = new HashMap<>();
//            group1Map.put("_id", groupIdMap);
//            group1Map.put("count", new BasicDBObject("$sum", 1));
//            DBObject group1 = new BasicDBObject("$group", group1Map);
//
//            /* 创建project1操作 */
//            Map<String, Object> project1Map = new HashMap<>();
//            project1Map.put("unit_id", "$_id.unit_id");
//            project1Map.put("unit_name", "$_id.unit_name");
//            project1Map.put("count", 1);
//            project1Map.put("_id", 0);
//            DBObject project1 = new BasicDBObject("$project", project1Map);
//
//            /* 创建sort操作*/
//            Map<String, Object> sortMap = new HashMap<>();
//            if (!StringUtils.isBlank(map.get("sort"))) {
//                sortMap.put("count", Integer.parseInt(map.get("sort")));
//            } else {
//                sortMap.put("count", -1);
//            }
//            DBObject sort = new BasicDBObject("$sort", sortMap);
//
//            DBCollection dbCollection = mongoTemplate.getCollection("tb_hidden_danger");
//            list.add(group1);
//            list.add(project1);
//            list.add(sort);
//            AggregationOutput aggregate = dbCollection.aggregate(list);
//            Iterable<DBObject> results = aggregate.results();
//
//            //整改
//
//
//
//            return new ResDto(Const.SUCCESS, "成功", results.toString());
//        } catch (Exception e) {
//            return new ResDto(Const.SERVER_ERROR, "失败");
//        }

        //第一个查询
        DBCollection dbCollection = mongoTemplate.getCollection("tb_hidden_danger");
        List<DBObject> list1 = getHiddenDangerImprove(msg, false);
        AggregationOutput aggregate1 = dbCollection.aggregate(list1);
        ArrayList<DBObject> results1 = (ArrayList) aggregate1.results();

//第二个查询【加人整改率】
        List<DBObject> list2 = getHiddenDangerImprove(msg, true);
        AggregationOutput aggregate2 = dbCollection.aggregate(list2);
        ArrayList<DBObject> results2 = (ArrayList) aggregate2.results();


        for (DBObject newDBObject1:results1) {
            String unitId1 = newDBObject1.get("unit_id").toString();

            boolean exists = false;
            for (DBObject newDBObject2:results2) {
                String unitId2 = newDBObject2.get("unit_id").toString();
                if (unitId2.equals(unitId1)) {
                    exists = true;
                    newDBObject1.put("rectify_count", newDBObject2.get("total"));
                    break;
                }
            }
            if (exists == false) {
                newDBObject1.put("rectify_count", 0);
            }
            int i=results1.indexOf(newDBObject1);
            results1.set(i, newDBObject1);
        }

//其他院系

        List<DBObject> list = new ArrayList<>();
        Map<String, String> map = JsonMapper.defaultMapper().fromJson(msg, Map.class);
        if (map == null) {
            return null;
        }
        if (!StringUtils.isBlank(map.get("show_all"))) {
            String show_all = map.get("show_all").toString();
            if (show_all.equals("1")) {

                List<UnitDomain> unitDomainListist = unitRepository.findAllByUnitTypeAndStatus("1", "0");

                for (UnitDomain model : unitDomainListist) {
                    boolean isExist = false;

                    for (DBObject newDBObject2:results1) {
                        String unitId = newDBObject2.get("unit_id").toString();
                        if (unitId.equals(model.getId())) {
                            isExist = true;
                            break;
                        }
                    }
                    if (isExist == false) {
                        DBObject dbObject = new BasicDBObject();
                        dbObject.put("total", "0");
                        dbObject.put("unit_name", model.getUnitName());
                        dbObject.put("unit_id", model.getId());
                        dbObject.put("rectify_count", "0");
                        results1.add(dbObject);
                    }
                }
            }
        }


        if (results1.size() > 0) {
            return new ResDto(Const.SUCCESS, "成功", JsonMapper.defaultMapper().toJson(results1));
        } else {
            return new ResDto(Const.SUCCESS, "成功", "{}");
        }
    }

    /**
     * 统计隐患记录整改率
     */
    @Override
    public ResDto getHiddenDangerRecordImproveStatistics(String msg) {

        //第一个查询
        DBCollection dbCollection = mongoTemplate.getCollection("tb_hidden_danger");
        List<DBObject> list1 = getHiddenDangerImprove(msg, false);
        AggregationOutput aggregate1 = dbCollection.aggregate(list1);
        ArrayList<DBObject> results1 = (ArrayList) aggregate1.results();

//        //第二个查询
//        List<DBObject> list2 = getHiddenDangerImprove(msg,true);
//        AggregationOutput aggregate2 = dbCollection.aggregate(list2);
//        ArrayList results2 = (ArrayList)aggregate2.results();
//
//
//        for (int i=0;i<results2.size();i++){
//            DBObject newDBObject2 = (DBObject)results2.get(i);
//            String unitId2 = newDBObject2.get("unit_id").toString();
//
//            for (int a=0;a<results1.size();a++) {
//                DBObject newDBObject1 = (DBObject)results1.get(a);
//                String unitId1 = newDBObject1.get("unit_id").toString();
//                if (unitId2.equals(unitId1)){
//                    newDBObject2.put("totle",newDBObject1.get("count"));
//                    break;
//                }
//            }
//            results2.set(i,newDBObject2);
//        }

        //第二个查询
        List<DBObject> list2 = getHiddenDangerImprove(msg, true);
        AggregationOutput aggregate2 = dbCollection.aggregate(list2);
        ArrayList<DBObject> results2 = (ArrayList) aggregate2.results();


        for (DBObject newDBObject1:results1) {
            String unitId1 = newDBObject1.get("unit_id").toString();

            boolean exists = false;
            for (DBObject newDBObject2:results2) {
                String unitId2 = newDBObject2.get("unit_id").toString();
                if (unitId2.equals(unitId1)) {
                    exists = true;
                    newDBObject1.put("rectify_count", newDBObject2.get("total"));
                    break;
                }
            }
            if (exists == false) {
                newDBObject1.put("rectify_count", 0);
            }
            int i=results1.indexOf(newDBObject1);
            results1.set(i, newDBObject1);
        }

        if (results1.size() > 0) {
            return new ResDto(Const.SUCCESS, "成功", JsonMapper.defaultMapper().toJson(results1));
        } else {
            return new ResDto(Const.SUCCESS, "成功", "{}");
        }
    }

    /**
     * 生成 word 整改报告
     *
     * @param reportDto
     * @return
     */
    @Override
    public ResDto getGenerateReport(GenerateReportByHiddendangerRecordDto reportDto) {
        List<String> hiddenDangerIds = reportDto.getHiddenDangerIds();
        String unitName = null;
        ArrayList<String> unitIds = new ArrayList<>();
        //院系级隐患
        List<HiddendangerRecordDto> unitHiddenDangerRecordList = new ArrayList<>();

        //实验室级隐患
        List<HiddendangerRecordDto> labHiddenDangerRecordList = new ArrayList<>();

        //实验室集合--可以看到有几个实验室
        List<LaboratoryDto> laboratoryDtoList = new ArrayList<>();
        List<String> laboratoryIdList = new ArrayList<>();

        List<UploadImageBase64Bean> base64ImgList = new ArrayList<>();
        for (String hiddenDangerId : hiddenDangerIds) {
            HiddendangerRecord one = hiddenDangerRecordRepository.findOne(hiddenDangerId);
            if (one == null) {
                return new ResDto(Const.PARAM_ERROR, hiddenDangerId + "不存在");
            }
            if (!unitIds.contains(one.getCheckUnitId())) {
                unitName = one.getCheckUnit();
                unitIds.add(one.getCheckUnitId());
            }
            if (unitIds.size() > 1) {
                return new ResDto(Const.SERVER_ERROR, "隐患记录不属于同一个院系,请重新选择");
            }

            HiddendangerRecordDto oneDto = BeanMapper.map(one, HiddendangerRecordDto.class);

            //查全部的整改信息按时间倒序
            List<RectifyReviewDto> zgList = rectifyReviewRepositoryImpl.findRectifyReview(hiddenDangerId, "0", RectifyReviewDomain.class, RectifyReviewDto.class);
            if (null != zgList && zgList.size() > 0) {
                RectifyReviewDto zgDto = zgList.get(0);
                //有图片,转成Base64
                RectifyReviewDto zgBase64Dto = zgfcPicPathToBase64(zgDto);
                base64ImgList.addAll(zgBase64Dto.getUploadImageBase64());
                //添加整改信息
                oneDto.setZhengGaiInfo(zgBase64Dto);
            }
            //查全部的复查信息按时间倒序
            List<RectifyReviewDto> fcList = rectifyReviewRepositoryImpl.findRectifyReview(hiddenDangerId, "1", RectifyReviewDomain.class, RectifyReviewDto.class);
            if (null != fcList && fcList.size() > 0) {
                RectifyReviewDto fcDto = fcList.get(0);
                //有图片,转成Base64
                RectifyReviewDto fcBase64Dto = zgfcPicPathToBase64(fcDto);
                base64ImgList.addAll(fcBase64Dto.getUploadImageBase64());
                //添加复查信息
                oneDto.setFuChaInfo(fcBase64Dto);
            }

            /**查询是否有院系和实验室的隐患记录**/
            CheckRecord checkRecordDomain = checkRecordsRepository.findOne(one.getCheckId());
            /**区分院系和实验室隐患记录**/
            //综合隐患
            if (null != checkRecordDomain && checkRecordDomain.getCheckType().equals("0")) {
                HiddendangerRecordDto oneBase64Dto = picPathToBase64(oneDto);
                base64ImgList.addAll(oneBase64Dto.getUploadImageBase64());
                unitHiddenDangerRecordList.add(oneBase64Dto);
            }
            //实验室隐患
            if (null != checkRecordDomain && checkRecordDomain.getCheckType().equals("1")) {
                String checkLabId = oneDto.getCheckLabId();
                //查出已经配置的危险源检查项的一级名称
                if (StringUtils.isNotBlank(checkLabId)) {
                    //得到一级的检查项名称
                    List<String> labInspectItemNames = new ArrayList<>();
                    //先查关系表
                    List<LabInspectItemRelationDomain> relationDomains = labInspectItemRelationRepository.findByLabId(checkLabId);
                    if (null != relationDomains && relationDomains.size() > 0) {
                        for (int m = 0; m < relationDomains.size(); m++) {
                            String inspectItemId = relationDomains.get(m).getInspectItemId();
                            //再查检查项表
                            LabInspectItemTreeDomain item = labInspectItemTreeRepository.findOne(inspectItemId);
                            //检查项类型是危险源：item_category为0
                            if (item.getItemLevel().equals("1")) {
                                if (item.getItemCategory().equals("0")) {
                                    String itemName = item.getItemName();
                                    if (!labInspectItemNames.contains(itemName)) {
                                        labInspectItemNames.add(itemName);
                                    }
                                }
                            } else {
                                LabInspectItemTreeDomain item2 = labInspectItemTreeRepository.findOne(item.getItemParentId());
                                String g;
                                //检查项类型是危险源：item_category为0
                                if (item2.getItemCategory().equals("0")) {
                                    String itemName2 = item2.getItemName();
                                    if (!labInspectItemNames.contains(itemName2)) {
                                        labInspectItemNames.add(itemName2);
                                    }
                                }
                            }
                        }
                    }

                    //危险源检查项的一级名称添加到隐患中
                    StringBuffer buffer = null;
                    if (labInspectItemNames.size() > 0) {
                        buffer = new StringBuffer();
                        for (String nameStr : labInspectItemNames) {
                            buffer.append(nameStr).append(";");
                        }
                        oneDto.setLabInspectItemNameStrs(buffer.toString());
                    }

                    //实验室信息对象添加到隐患中
                    LaboratoryDomain labDomain = laboratoryRepository.findOne(checkLabId);
                    if (!laboratoryIdList.contains(checkLabId) && null != labDomain) {
                        laboratoryIdList.add(checkLabId);
                        LaboratoryDto labDto = BeanMapper.map(labDomain, LaboratoryDto.class);
                        oneDto.setLaboratory(labDto);
                        labDto.setLabInspectItemNameStrs(buffer == null ? "" : buffer.toString());
                        laboratoryDtoList.add(labDto);

                        //实验室集合--(防止同一个实验室的隐患显示多条实验室信息)
                        /*if (laboratoryDtoList.size() > 0) {
                            for (int i = 0; i < laboratoryDtoList.size(); i++) {
                                if (!laboratoryDtoList.get(i).getId().equals(labDto.getId())) {
                                    //危险源检查项的一级名称添加到实验室中去
                                    labDto.setLabInspectItemNameStrs(buffer == null ? "" : buffer.toString());
                                    laboratoryDtoList.add(labDto);
                                }
                            }
                            *//**解决ConcurrentModificationException异常*//*

//                            for (LaboratoryDto lablab : laboratoryDtoList) {
//                                if (!lablab.getId().equals(labDto.getId())) {
//                                    //危险源检查项的一级名称添加到实验室中去
//                                    labDto.setLabInspectItemNameStrs(buffer == null ? "" : buffer.toString());
//                                    laboratoryDtoList.add(labDto);
//                                }
//                            }
                        } else {
                            //危险源检查项的一级名称添加到实验室中去
                            labDto.setLabInspectItemNameStrs(buffer == null ? "" : buffer.toString());
                            laboratoryDtoList.add(labDto);
                        }*/
                    }
                }
                HiddendangerRecordDto oneBase64Dto = picPathToBase64(oneDto);
                base64ImgList.addAll(oneBase64Dto.getUploadImageBase64());
                labHiddenDangerRecordList.add(oneDto);
            }
        }


        NoticeBookExportWordDto nBWordDto = new NoticeBookExportWordDto();

        NoticeBookReturnDto noticeBookReturnDto = new NoticeBookReturnDto();
        //院系
        noticeBookReturnDto.setNoticeReceiveUnitName(unitName);
        nBWordDto.setNoticeBookDto(noticeBookReturnDto);

        //综合隐患
        nBWordDto.setUnitRecords(unitHiddenDangerRecordList);
        //实验室隐患
        nBWordDto.setLabRecords(labHiddenDangerRecordList);
        nBWordDto.setLabList(laboratoryDtoList);


        //生成word整改报告
        Map<String, Object> datasMap = new HashMap<String, Object>(4);
        datasMap.put("nBWordDto", nBWordDto);
        datasMap.put("imgs", base64ImgList);

        // /生成word文档
        DocumentHandler documentHandler = new DocumentHandler();
        ResDto resDto = new ResDto();
        try {
            /**生成word 2003**/
            //这是本地测试
            //documentHandler.createDoc("template_noticebook.ftl", datasMap, "E:/noticebook" + (new Date().getTime()) + ".doc");

//            //拼接服务器上的路径地址
//            String path = "/word/";
//            String roleId = "1";
//            String date = DateFormatUtil.formatDate(DateFormatUtil.PATTERN_ISO_ON_DATE, new Date());
//            path += roleId + "/" + date + "/";
//            //保存文件
//            String exprotFilepath = filePath + path;
//            File dir = new File(exprotFilepath);
//            //File dir = new File(path);
//            if (!dir.exists()) {
//                dir.mkdirs();
//            }
//            //保存word的地址
//            String fileName = "report" + new Date().getTime() + ".doc";
//            String saveFileNameAndPath = exprotFilepath + fileName;
//            documentHandler.createDoc("template_noticebook.ftl", datasMap, saveFileNameAndPath);
//            resDto.setStatus(Const.SUCCESS);
//            resDto.setMsg("成功");
//            //下载word的地址
//            String downLoadFileNameAndPath = urlPath + path + fileName;
//            resDto.setDatas(downLoadFileNameAndPath);

            /**生成word 2013**/
            String path = "/word/";
            String roleId = "1";
            String date = DateFormatUtil.formatDate(DateFormatUtil.PATTERN_ISO_ON_DATE, new Date());
            path += roleId + "/" + date + "/";
            //保存文件
            String exprotFilepath = filePath + path;
            File dir = new File(exprotFilepath);
            //File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //保存word的地址
            String fileName = "report" + new Date().getTime() + ".docx";
            String saveFileNameAndPath = exprotFilepath + fileName;
            //documentHandler.createDoc("template_noticebook.ftl", datasMap, saveFileNameAndPath);
            //生成docx 2013word
            File resumeFile = WordTools.createDoc("template_noticebook_2013.xml", datasMap, "template_noticebook_2013.ftl");
            WordprocessingMLPackage wmlPackage = null;
            try {
                wmlPackage = (WordprocessingMLPackage) WordprocessingMLPackage.load(new FileInputStream(resumeFile));
            } catch (Docx4JException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            File file = new File(saveFileNameAndPath);
            try {
                wmlPackage.save(file, Docx4J.FLAG_SAVE_ZIP_FILE);
            } catch (Docx4JException e) {
                e.printStackTrace();
            }

            resDto.setStatus(Const.SUCCESS);
            resDto.setMsg("成功");
            //下载word的地址
            String downLoadFileNameAndPath = urlPath + path + fileName;
            resDto.setDatas(downLoadFileNameAndPath);
        } catch (Exception e) {//UnsupportedEncodingException e
            e.printStackTrace();
            resDto.setStatus(Const.DATA_ERROR);
            resDto.setMsg("生成整改报告异常");
        }
        return resDto;
    }

    /**
     * 隐患图片转成Base64编码
     *
     * @param hiddendangerRecord
     */
    public HiddendangerRecordDto picPathToBase64(HiddendangerRecordDto hiddendangerRecord) {
        //隐患记录中的图片
        List<UploadImage> uploadImageList = hiddendangerRecord.getUploadImageList();
        List<UploadImageBase64Bean> base64List = new ArrayList<>();
        if (null != uploadImageList && uploadImageList.size() > 0) {
            for (int j = 0; j < uploadImageList.size(); j++) {
                //图片地址转成Base64
                UploadImage uploadImageconvert = new UploadImage();
                //类型转换
                BeanUtils.copyProperties(uploadImageList.get(j), uploadImageconvert);
                if (StringUtils.isNotBlank(uploadImageconvert.getPath())) {
                    //网络获取图片
                    String base64PicStr = Base64Util.GetImageStrFromUrl(urlPath + uploadImageconvert.getPath());
                    UploadImageBase64Bean base64Bean = new UploadImageBase64Bean();
                    base64Bean.setUploadImageBase64(base64PicStr);
                    base64Bean.setPicId(IdGenerator.uuid2());
                    base64List.add(base64Bean);
                }
            }
        }
        hiddendangerRecord.setUploadImageBase64(base64List);
        return hiddendangerRecord;
    }

    /**
     * 整改复查图片转成Base64编码
     *
     * @param rectifyReviewDto
     */
    public RectifyReviewDto zgfcPicPathToBase64(RectifyReviewDto rectifyReviewDto) {
        //隐患记录中的图片
        List<UploadImage> uploadImageList = rectifyReviewDto.getUploadImageList();
        List<UploadImageBase64Bean> base64List = new ArrayList<>();
        if (null != uploadImageList && uploadImageList.size() > 0) {
            for (int j = 0; j < uploadImageList.size(); j++) {
                //图片地址转成Base64
                UploadImage uploadImageconvert = new UploadImage();
                //类型转换
                BeanUtils.copyProperties(uploadImageList.get(j), uploadImageconvert);
                if (StringUtils.isNotBlank(uploadImageconvert.getPath())) {
                    //网络获取图片
                    String base64PicStr = Base64Util.GetImageStrFromUrl(urlPath + uploadImageconvert.getPath());
                    UploadImageBase64Bean base64Bean = new UploadImageBase64Bean();
                    base64Bean.setUploadImageBase64(base64PicStr);
                    base64Bean.setPicId(IdGenerator.uuid2());
                    base64List.add(base64Bean);
                }
            }
        }
        rectifyReviewDto.setUploadImageBase64(base64List);
        return rectifyReviewDto;
    }

    public List<DBObject> getHiddenDangerImprove(String msg, Boolean hasImproved) {
        try {
            List<DBObject> list = new ArrayList<>();
            Map<String, String> map = JsonMapper.defaultMapper().fromJson(msg, Map.class);
            if (map == null) {
                return null;
            }
            //条件查询
            /*按检查项查询*/
            Map<String, Object> matchMap = new HashMap<>();
            if (StringUtils.isNotBlank(map.get("level")) && StringUtils.isNotBlank(map.get("check_item_id"))) {
                String level = map.get("level").toString();
                String check_item_id = map.get("check_item_id");
                if (level.equals("1")) {
                    matchMap.put("check_item_one_id", check_item_id);
                } else if (level.equals("2")) {
                    matchMap.put("check_item_two_id", check_item_id);
                }
            }
            Map<String, Object> timeMap = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            /*按日期查询*/
            if (!StringUtils.isBlank(map.get("start_date"))) {

                Date start_date = simpleDateFormat.parse(map.get("start_date").toString());
                timeMap.put("$gte", start_date);
            }
            if (!StringUtils.isBlank(map.get("end_date"))) {
                Date end_date = simpleDateFormat.parse(map.get("end_date").toString());
                timeMap.put("$lte", end_date);
            }
            if (timeMap.size() > 0) {
                matchMap.put("gmt_created", timeMap);
            }
            matchMap.put("check_status", "3"); //状态为”已审核“的检查记录中的隐患记录

            if (hasImproved == true) {
                matchMap.put("hidden_danger_status", "3"); //状态为”已整改“
            }

            DBObject match = new BasicDBObject("$match", matchMap);
            list.add(match);

            /* 创建group1操作 */
            Map<String, String> groupIdMap = new HashMap<>();
            groupIdMap.put("unit_id", "$check_unit_id");
            groupIdMap.put("unit_name", "$check_unit");

            Map<String, Object> group1Map = new HashMap<>();
            group1Map.put("_id", groupIdMap);
            group1Map.put("total", new BasicDBObject("$sum", 1));
            DBObject group1 = new BasicDBObject("$group", group1Map);

            /* 创建project1操作 */
            Map<String, Object> project1Map = new HashMap<>();
            project1Map.put("unit_id", "$_id.unit_id");
            project1Map.put("unit_name", "$_id.unit_name");
            project1Map.put("total", 1);
            project1Map.put("_id", 0);
            DBObject project1 = new BasicDBObject("$project", project1Map);

            /* 创建sort操作*/
//            Map<String, Object> sortMap = new HashMap<>();
//            if (!StringUtils.isBlank(map.get("sort"))) {
//                sortMap.put("total", Integer.parseInt(map.get("sort")));
//            } else {
//                sortMap.put("total", 1);
//            }
//            DBObject sort = new BasicDBObject("$sort", sortMap);

            DBCollection dbCollection = mongoTemplate.getCollection("tb_hidden_danger");
            list.add(group1);
            list.add(project1);
//            list.add(sort);
            return list;
        } catch (Exception e) {
            return null;
        }
    }
}
